import { request } from '@/utils/request'
import { crudApi, fileApi } from './common'
import type { 
  LoginParams, 
  LoginResponse, 
  UserInfoResponse, 
  UserQuery, 
  UserCreateForm,
  UserUpdateForm,
  ProfileForm,
  ResetPasswordForm,
  ChangePasswordForm,
  ImportResult,
  UserDetail
} from '@/types/user'
import type { PageResponse } from '@/types/api'

// 用户API基础路径
const USER_BASE_URL = '/system/user'

// 认证相关API
export const loginApi = (data: LoginParams): Promise<LoginResponse> => {
  return request.post('/auth/login', data)
}

export const getUserInfoApi = (): Promise<UserInfoResponse> => {
  return request.get('/auth/userinfo')
}

export const logoutApi = (): Promise<void> => {
  return request.post('/auth/logout')
}

export const refreshTokenApi = (): Promise<LoginResponse> => {
  return request.post('/auth/refresh')
}

export const getCaptchaApi = (): Promise<{ captchaKey: string; captchaImage: string }> => {
  return request.get('/auth/captcha')
}

// 用户管理API - 使用通用CRUD工具
export const getUserListApi = (params: UserQuery): Promise<PageResponse<UserDetail>> => {
  return crudApi.getPageList<UserDetail>(`${USER_BASE_URL}/page`, params)
}

export const getUserDetailApi = (id: number): Promise<UserDetail> => {
  return crudApi.getDetail<UserDetail>(USER_BASE_URL, id)
}

export const addUserApi = (data: UserCreateForm): Promise<void> => {
  return crudApi.create(USER_BASE_URL, data)
}

export const updateUserApi = (data: UserUpdateForm): Promise<void> => {
  return crudApi.update(USER_BASE_URL, data)
}

export const deleteUserApi = (ids: number[]): Promise<void> => {
  return crudApi.delete(USER_BASE_URL, ids)
}

// 用户特定功能API
export const resetPasswordApi = (data: ResetPasswordForm): Promise<void> => {
  return request.put(`${USER_BASE_URL}/resetPwd`, data)
}

export const changePasswordApi = (data: ChangePasswordForm): Promise<void> => {
  return request.put(`${USER_BASE_URL}/changePwd`, data)
}

export const updateProfileApi = (data: ProfileForm): Promise<void> => {
  return request.put(`${USER_BASE_URL}/profile`, data)
}

// 文件操作API - 使用通用文件工具
export const uploadAvatarApi = (file: File): Promise<{ url: string }> => {
  return fileApi.upload({ file, folder: 'avatar' })
}

export const exportUserApi = (params: UserQuery): Promise<void> => {
  return fileApi.download({ 
    url: `${USER_BASE_URL}/export`, 
    params, 
    filename: '用户列表.xlsx' 
  })
}

export const downloadTemplateApi = (): Promise<void> => {
  return fileApi.download({ 
    url: `${USER_BASE_URL}/importTemplate`, 
    filename: '用户导入模板.xlsx' 
  })
}

export const importUserApi = (file: File): Promise<ImportResult> => {
  return request.upload(`${USER_BASE_URL}/import`, file)
}
